<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">

            <div class="progressHint" v-if="hint">
              <NIcon size="20" class="iconStyle">
                <ErrorRound />
              </NIcon>
              <div style="white-space: pre-wrap" v-html="hint"></div>
            </div>
            <div class="progress">
              <div style="display:flex; margin-right: 10rem;">
                <NIcon :size="20" class="iconStyle">
                  <ApprovalFilled />
                </NIcon>
                <span>审批流程</span>
              </div>
              <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
              </span>
            </div>

            <div class="content_cen">
              <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="110"
                :model="formValue" style="width: 350rem" label-align="right">
                <NSpace justify="space-between">
                  <NFormItem label="出发时间:" path="departureTime">
                    <NDatePicker input-readonly placeholder="请选择出发时间" class="commonWidth"
                      v-model:formatted-value="formValue.departureTime" type="date" clearable
                      :is-date-disabled="handleDateA" />
                  </NFormItem>
                  <NFormItem label="返回时间:" path="returnTime">
                    <NDatePicker input-readonly placeholder="请选择返回时间" class="commonWidth"
                      v-model:formatted-value="formValue.returnTime" type="date" clearable
                      :is-date-disabled="handleDate" />
                  </NFormItem>
                </NSpace>
                <NSpace>
                  <NFormItem label="出差天数:" path="errandDay">
                    <NInput placeholder="出差天数" class="commonWidth" disabled v-model:value="formValue.errandDay" />
                  </NFormItem>
                </NSpace>
                <NFormItem label="出差行程:" path="km">
                  <div style="display: flex; justify-content: space-between; width: 100%">
                    <div style="display: flex; flex-wrap: wrap">
                      <div v-for="(item, index) in formValue.errandTripList" :key="index" style="
                        display: flex;
                        align-items: flex-start;
                        width: 400rem;
                        height:40px;
                        margin-bottom:20px;
                      ">
                        <NFormItem :path="`errandTripList[${index}].departureLocation`" :rule="{
                          required: false,
                          validator: (e: any, value: any) => renderMessage(value),
                          trigger: ['input', 'blur']
                        }">
                          <NInput placeholder="出差行程" :allow-input="stopNull" class="commonWidthB"
                            v-model:value="item.departureLocation" />
                        </NFormItem>
                        <div style="height: 34rem; line-height: 34rem; margin: 0 5rem">至</div>
                        <NFormItem :path="`errandTripList[${index}].destination`" :rule="{
                          required: false,
                          validator: (e: any, _: any) => renderMessageEnd(_),
                          trigger: ['input', 'blur']
                        }">
                          <NInput placeholder="出差行程" :allow-input="stopNull" class="commonWidthB"
                            v-model:value="item.destination" />
                        </NFormItem>
                        <NButton circle type="error" size="tiny" style="margin-left: 10px;margin-top:5px"
                          v-if="formValue.errandTripList.length > 1" @click="DeteleTrip(item)">
                          <div style="height: 34rem; line-height: 34rem">—</div>
                        </NButton>
                      </div>
                    </div>
                  </div>

                </NFormItem>
                <NFormItem label=" ">
                  <NButton style="width: 115rem" type="primary" @click="AddTrip" ghost>
                    添加行程
                  </NButton>
                </NFormItem>

                <NSpace style="display: flex; flex-direction: column">
                  <NFormItem label="同伴:" path="scopeOrPeopleList">
                    <div style="width: 100%">
                      <NButton style="width: 115px;margin-bottom: 15px;" type="primary" @click="openScope" ghost>
                        选择同伴
                      </NButton>
                      <div style="width: 100%;overflow: hidden;height: 120rem;background-color: #e1e1e1;
                      padding: 10px 15px;" v-if="formValue.scopeOrPeopleList?.length">
                        <NScrollbar>
                          <div class="scope">
                            <div class="userBox" v-for="(item, index) in formValue.scopeOrPeopleList" :key="index">
                              <div>{{ item.typeName }}</div>
                              <n-icon @click="handleScope(item.identifyingId)" style="cursor: pointer">
                                <CloseFilled />
                              </n-icon>
                            </div>
                          </div>
                        </NScrollbar>
                      </div>
                    </div>
                  </NFormItem>
                </NSpace>

                <NFormItem label="是否省内:" path="provinceFlag">
                  <NSelect placeholder="请选择是否在省内" class="commonWidth" :options="[
                    {
                      value: '1',
                      label: '否'
                    },
                    {
                      value: '0',
                      label: '是'
                    }
                  ]" v-model:value="formValue.provinceFlag" @update-value="changeProvice" />
                </NFormItem>

                <NFormItem label="交通工具:" path="travelModeCodeList">
                  <NSelect multiple :options="vehicleList" v-model:value="formValue.travelModeCodeList"
                    class="commonWidth" :render-option="renderOption" />
                </NFormItem>
                <NFormItem label="出差事由:" path="reasons">
                  <NInput placeholder="请输入出差事由" :allow-input="stopNull" v-model:value="formValue.reasons"
                    style="min-height: 100rem" type="textarea" />
                </NFormItem>
                <NFormItem label="附件:" path="fileId">
                  <VUpload :file-list="fileList" @getList="handleUploadList" />
                </NFormItem>
              </NForm>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(1)" :loading="loading"
          v-if="workFlowList">
          保存草稿
        </NButton>
        <NButton type="primary" @click="confirm(0)" :loading="loading" v-if="workFlowList">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>
  <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
    <VScope @close="modalVisible = false" @scopeSubmit="getScopeList" :defaultList="scopeList" :flat="true" />
  </NModal>

  <NModal :auto-focus="false" v-model:show="modalVisibleA">
    <VDialogContent @close="modalVisibleA = false" @submit="modalVisibleA = false" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center;display: flex;align-items: center">
        {{ contentContent }}
      </div>
      <div style="text-align: center;" v-if="repeatFormUrl.path !== ''">
        <NButton type="primary" text style="font-size: 14px;" @click="openRepeatUrl()">
          点此
        </NButton>查看重复工单
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, h, type VNode } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NDatePicker,
  NButton,
  NScrollbar,
  NIcon,
  NModal,
  NSpin,
  useMessage,
  NSelect,
  NTooltip,
  type SelectOption,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { CloseFilled } from '@vicons/material'
import VScope from '@/views/OA/Common/Scope.vue'
import VUpload from '@/views/OA/Common/Upload.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute } from 'vue-router'
import { workFlow } from '@/enums/workFlow'
import VBackImg from '@/assets/images/back.png'
import { ApprovalFilled } from '@vicons/material'
import type { FormRules } from 'naive-ui'
import { subDays } from 'date-fns'
import { ErrorRound } from '@vicons/material'

const tags = useTagStore().tags
const message = useMessage()
const route = useRoute()

const props = defineProps({
  title: { type: String, default: () => '出差申请' },
  id: { type: [Number, String], default: () => null },
  flag: { type: [Number, String], default: () => null }
})

const spinShow = ref(false)

//去除空格
const stopNull = (value: string) => {
  return !value.startsWith(' ') && !value.endsWith(' ')
}

const formValue = reactive<Record<string, any>>({
  km: null,
  draft: null, //草稿状态
  entityId: null, //流程实体id
  departureTime: null, //出发时间
  returnTime: null, //预计返回时间
  errandDay: null, //出差天数
  scopeOrPeopleList: null, //发布范围
  errandTripList: [
    {
      departureLocation: null, //出发地
      destination: null //目的地
    }
  ],
  travelModeCodeList: null,
  reasons: null, //出差事由
  fileId: null, //文件id
  provinceFlag: null
})
const rules: FormRules = {
  departureTime: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择出发时间'
  },
  returnTime: {
    required: true,
    message: '请选择返回时间',
    trigger: ['change']
  },
  errandDay: {
    required: true,
    message: '',
    trigger: ['input']
  },
  provinceFlag: {
    required: true,
    message: '请选择是否省内',
    trigger: ['blur', 'change']
  },
  km: {
    required: true,
    trigger: ['input', 'change'],
    message: '请填写行程'
  },
  travelModeCodeList: [
    {
      type: 'array',
      required: true,
      trigger: 'change',
      message: '请选择交通工具'
    }
  ],
  reasons: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写出差事由')
      if (value.length > 100) return new Error('出差事由不得超过100字')
      return true
    }
  }
}

const renderMessage = (value: any) => {
  if (value?.length > 100) return new Error('不得超过100字')
  return true
}
const renderMessageEnd = (value: any) => {
  if (value?.length > 100) return new Error('不得超过100字')
  return true
}

// 日期禁用
const handleDate = (ts: any) => {
  return ts < new Date(subDays(new Date(formValue.departureTime), 1))
}

const handleDateA = (ts: any) => {
  if (formValue.returnTime) {
    return ts > new Date(new Date(formValue.returnTime))
  } else {
    return false
  }
}

const renderOption = ({
  node,
  option
}: {
  node: VNode
  option: SelectOption
}) =>
  h(
    NTooltip,
    {
      placement: 'left'
    },
    {
      trigger: () => node,
      default: () => option.label
    }
  )

//省内外
const changeProvice = (val: any) => {
  formValue.provinceFlag = val
  getWorkFlow()
}

//同伴
const scopeList = ref()
const modalVisible: any = ref(false)
const openScope = () => {
  scopeList.value = formValue.scopeOrPeopleList
  modalVisible.value = true
}

// 发布范围选择
const getScopeList = (v: any) => {
  formValue.scopeOrPeopleList = v
  modalVisible.value = false
}
// 范围选择是删除
const handleScope = (id: any) => {
  const index = formValue.scopeOrPeopleList.findIndex((it: any) => it.identifyingId == id)
  formValue.scopeOrPeopleList.splice(index, 1)
}

//行程
const DeteleTrip = (val: any) => {
  formValue.errandTripList = formValue.errandTripList.filter((item: any) => item != val)
}

const AddTrip = () => {
  formValue.errandTripList.push({
    departureLocation: '',
    destination: ''
  })
}

//交通工具
const vehicleList: any = ref([])
const getVehicleType = async () => {
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'roomType',
    override: {
      params: {
        dicCode: 'A12'
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  vehicleList.value = []
  res.data.map((i: any) => {
    vehicleList.value.push({
      label: i.dicName,
      value: i.dicCode
    })
  })
}
getVehicleType()

// 获取流程id
const hint = ref()
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: formValue.errandDay < 3 && formValue.provinceFlag == '0' ? workFlow.CCSQLC3TYN : workFlow.CCSQLC3TYS
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
}
getWorkFlow()

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}

// 附件
const handleUploadList = (v: any) => (formValue.fileId = v)

// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const modalVisibleA = ref(false)
const contentContent = ref()
interface repeatFormUrlState {
  path: string;
  params: {
    [key: string] : any;
  }
}
const repeatFormUrl = reactive<repeatFormUrlState>({
  path: "",
  params: {}
}) // 是否有重复工单的url
const confirm = (status: number) => {
  formValue.draft = status
  formRef.value?.validate(async (err) => {
    if (err) return
    const startTime = formValue.departureTime ? formValue.departureTime + ' ' + '07:00:00' : ''
    const endTime = formValue.returnTime ? formValue.returnTime + ' ' + '19:00:00' : ''
    const [errorCheck, resCheck] = await sendRequest({
      module: 'overTime',
      api: 'getWorkOvertimeApplyCheck1',
      override: {
        data: {
          type: 3,
          startTime: startTime,
          endTime: endTime,
          ids: formValue.scopeOrPeopleList?.map((it: any) => it.identifyingId)
        }
      }
    })
    if (errorCheck) return message.error(errorCheck.message)
    if (resCheck.code !== 0) return message.error(resCheck.msg)
    // if (resCheck.data as never !== '可以提交') return message.error(resCheck.data as never)
    const { prompt, promptFlag, promptId, typeNumber } = (resCheck.data as any)
      if(promptFlag) {
        modalVisibleA.value = true
        contentContent.value = prompt
        if(typeNumber !== 0) {
          if(typeNumber == 3) {
            repeatFormUrl.path = '/OA/Onbusiness/MineApplicationDetail',
            repeatFormUrl.params = { id: promptId }
          }
        }
      } else {
        // contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
        againConfirm()
      }
  })
}
// 打开重复的url
const openRepeatUrl = () => {
  if(repeatFormUrl) {
    router.push({ path: repeatFormUrl.path, query: { ...repeatFormUrl.params } })
    modalVisibleA.value = false
    repeatFormUrl.path = ''
    repeatFormUrl.params = {}
  }
}
const againConfirm = async () => {
  const tmp: any = JSON.parse(JSON.stringify(formValue))
  delete tmp['km']
  if (props.id && !props.flag) {
    const [error, res] = await sendRequest({
      module: 'application',
      api: 'applicationUpdate',
      override: {
        data: {
          ...tmp,
          id: props?.id,
          userName: userName.value
        }
      }
    })
    if (error) return message.error(error.message)
    message.success(res.msg)
    goSubmit()
  } else {
    const [error, res] = await sendRequest({
      module: 'application',
      api: 'applicationSave',
      override: {
        data: tmp
      }
    })
    if (error) return message.error(error.message)
    message.success(res.msg)
    goSubmit()
  }
  modalVisibleA.value = false
}


//提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}

//获取修改详情
const fileList: any = ref([])
const userName = ref()
const getInfo = async () => {
  await getVehicleType()
  const [error, res] = await sendRequest({
    module: 'application',
    api: 'applicationItem',
    uri: {
      id: props.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data.fileList
  userName.value = res.data.userName
  Object.keys(formValue).map((it: any) => {
    if (it == 'provinceFlag') {
      if (res.data?.provinceFlag) {
        formValue.provinceFlag = '1'
      } else {
        formValue.provinceFlag = '0'
      }
    } else {
      // @ts-ignore
      formValue[it] = res.data[it]
    }
  })
  await getWorkFlow()
}


//计算天数
function getDaysBetweenDates(date1: any, date2: any) {
  const oneDay = 24 * 60 * 60 * 1000
  const firstDate = new Date(date1)
  const secondDate = new Date(date2)
  const diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / oneDay)) + 1
  return (formValue.errandDay = diffDays + '')
}

watch(
  () => formValue.departureTime && formValue.returnTime,
  async () => {
    if (formValue.departureTime && formValue.returnTime) {
      await getDaysBetweenDates(formValue.returnTime, formValue.departureTime)
      if (formValue.provinceFlag) {
        await getWorkFlow()
      }
    }
  },
  { deep: true, immediate: true }
)

watch(
  () => formValue.errandTripList,
  () => {
    const flag1 = formValue.errandTripList.every((it: any) => it.departureLocation)
    const flag2 = formValue.errandTripList.every((it: any) => it.destination)
    flag1 && flag2 ? (formValue.km = '1') : (formValue.km = null)
  },
  { deep: true }
)

watch(
  () => props.id,
  () => {
    if (props.title == '出差申请编辑' && props.id) getInfo()
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.commonWidthB {
  width: 105rem;
}

@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;


      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          min-height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 350rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 350rem;
  max-width: 800rem;
  padding: 5px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
